package com.campus.chat.ws;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.campus.chat.config.GetHttpSessionConfig;
import com.campus.chat.utils.MessageUtils;
import com.campus.chat.ws.pojo.Message;
import com.campus.pojos.domain.ChatList;
import com.campus.pojos.domain.ChatMessage;
import com.campus.service.ChatListService;
import com.campus.service.ChatMessageService;
import com.campus.service.UserService;
import com.campus.service.impl.ChatListServiceImpl;
import com.campus.service.impl.ChatMessageServiceImpl;
import com.campus.utils.SpringCtxUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


@ServerEndpoint("/client/chat/{id}")
@Component
@Slf4j
@SuppressWarnings("all")
public class ChatEndpoint {

    private static final Map<String,Session> onlineUsers = new ConcurrentHashMap<>();


    private static ChatListService chatListService;

    private static ChatMessageService chatMessageService;

    @Autowired
    public void setChatListService(ChatListService chatListService) {
        ChatEndpoint.chatListService = chatListService;
    }
    @Autowired
    public void setChatMessageService(ChatMessageService chatMessageService) {
        ChatEndpoint.chatMessageService = chatMessageService;
    }

    /**
     * 建立websocket连接后，被调用
     * @param session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        log.info("id: {}",id);
        log.info("session: {}", session);
        onlineUsers.put(id,session);
        //1，将session进行保存
        //this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        //String user = (String) this.httpSession.getAttribute("user");

        //onlineUsers.put(user,session);
        //2，广播消息。需要将登陆的所有的用户推送给所有的用户
//        String message = MessageUtils.getMessage(true,null,getFriends());
//        broadcastAllUsers(message);
    }

    public Set getFriends() {
        Set<String> set = onlineUsers.keySet();
        return set;
    }

    private void broadcastAllUsers(String message) {
        try {
            //遍历map集合
            Set<Map.Entry<String, Session>> entries = onlineUsers.entrySet();
            for (Map.Entry<String, Session> entry : entries) {
                //获取到所有用户对应的session对象
                Session session = entry.getValue();
                //发送消息
                session.getBasicRemote().sendText(message);
            }
        } catch (Exception e) {
            //记录日志
        }
    }

    /**
     * 浏览器发送消息到服务端，该方法被调用
     *
     * 张三  -->  李四
     * @param message
     */
    @OnMessage
    public void onMessage(String message) {
        try {
            //将消息推送给指定的用户
            Message msg = JSON.parseObject(message, Message.class);
            //获取 消息接收方的用户名
            String fromUserId = msg.getFromUserId();
            String toUserId = msg.getToUserId();
            String mess = msg.getMessage();

            log.info("发送者用户id:{} 接收者id:{} 消息:{}",fromUserId,toUserId,mess);
            //将消息存入数据库
            ChatMessage chatMessage = new ChatMessage();
            chatMessage.setFromUserId(Long.parseLong(fromUserId));
            chatMessage.setToUserId(Long.parseLong(toUserId));
            chatMessage.setContent(mess);
            chatMessage.setSendTime(LocalDateTime.now());

            chatMessageService.save(chatMessage);

            //建立聊天关系
            QueryWrapper<ChatList> qw = new QueryWrapper<>();
            qw.eq("from_user_id",msg.getFromUserId());
            qw.eq("to_user_id",msg.getToUserId());

            ChatList chatListAtoB = chatListService.getOne(qw);
            qw = new QueryWrapper<>();
            qw.eq("from_user_id",msg.getToUserId());
            qw.eq("to_user_id",msg.getFromUserId());
            ChatList chatListBtoA = chatListService.getOne(qw);

            //1.1判断是否是第一次聊天
            if(chatListAtoB == null && chatListBtoA == null){
                //是第一次聊天,建立联系存入数据库中
                //1.1.1建立AtoB的list
                chatListAtoB = new ChatList();
                chatListAtoB.setFromUserId(Long.parseLong(fromUserId));
                chatListAtoB.setToUserId(Long.parseLong(toUserId));
                chatListAtoB.setUnread(0);
                chatListService.save(chatListAtoB);
                //1.1.2 建立BtoA的list 未读默认置为1
                chatListBtoA = new ChatList();
                chatListBtoA.setUnread(1);
                chatListBtoA.setFromUserId(Long.parseLong(toUserId));
                chatListBtoA.setToUserId(Long.parseLong(fromUserId));
                chatListService.save(chatListBtoA);
//                //判断接收者是否在线
//                if(!onlineUsers.containsKey(toUserId)) chatList.setUnread(1);
//                chatListService.save(chatList);
            }else{
                //不是第一次聊天,则只需要修改未读数
                //判断接收者是否在线
                if(!onlineUsers.containsKey(toUserId)){
                    chatListBtoA.setUnread(chatListBtoA.getUnread() + 1);
                    chatListService.updateById(chatListBtoA);
                }
            }

            //获取消息接收方用户对象的session对象
            Session session = onlineUsers.get(toUserId);
            String msg1 = MessageUtils.getMessage(false, fromUserId, mess);
            session.getBasicRemote().sendText(msg1);
        } catch (Exception e) {
            //记录日志
        }
    }

    /**
     * 断开 websocket 连接时被调用
     * @param session
     */
    @OnClose
    public void onClose(Session session, @PathParam("id") String id) {
        log.info("用户id:{}", id);
        onlineUsers.remove(id);
        //1,从onlineUsers中剔除当前用户的session对象
//        String user = (String) this.httpSession.getAttribute("user");
//        onlineUsers.remove(user);
//        //2,通知其他所有的用户，当前用户下线了
//        String message = MessageUtils.getMessage(true,null,getFriends());
//        broadcastAllUsers(message);
    }
}
